package cn.tedu._03vehicle.controller;

import cn.tedu._03vehicle.base.response.JsonResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@RestController
@Tag(name = "04-文件上传模块")
@RequestMapping("/v1/file/")
public class UploadController {
    @PostMapping("upload")
    @Operation(summary = "01-文件上传")
    @ApiOperationSupport(order = 10)
    public JsonResult upload(MultipartFile file) throws IOException {
          /*
            1.接收客户端传递的数据[图片];
            2.将文件保存到服务器的指定目录[d:/files];
            3.返回响应;
         */
        // ********终极目标: d:/files/2025/06/17/138e8728-a2bc-47b4-9127-b73226feb898.jpg
        //*********************第1步:处理文件名************************
        // 1.1 原始文件名filename: Powder.jpg
        String filename = file.getOriginalFilename();
        // 1.2 获取文件后缀suffix: .jpg
        String suffix = filename.substring(filename.lastIndexOf("."));
        // 1.3 生成全球唯一的UUID: 138e8728-a2bc-47b4-9127-b73226feb898
        UUID uuid = UUID.randomUUID();
        // 1.4 拼接完整的唯一文件名：138e8728-a2bc-47b4-9127-b73226feb898.jpg
        filename = uuid + suffix;
        //********************第2步:处理文件保存的路径**********************
        // 2.1 服务器静态资源路径
        String dirPath = "d:/files";
        // 2.2 自定义日期路径：/yyyy/MM/dd/ 比如:/2025/06/17/
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        // 2.3 创建对应的目录：d:/files/2025/06/17/
        File file1 = new File(dirPath + datePath);
        if (!file1.exists()){
            file1.mkdirs();
        }
        //********************第3步:保存文件到服务器**********************
        String filePath = dirPath + datePath + filename;
        file.transferTo(new File(filePath));
        //*********************第4步:返回响应***************************
        //后端: {"state":2000,"message":"操作成功", "data": ""}
        //前端: 获取data的值,并在浏览器中显示该图片;
        //     http://localhost:8080/2025/06/17/138e8728-a2bc-47b4-9127-b73226feb898.jpg
        return JsonResult.ok(datePath + filename);
    }
}
